package server

import (
	dev "dashboard/device"
	"dashboard/web"
	"fmt"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/filesystem"
	"log"
	"os/exec"
	"time"
)

func routerAPI(api fiber.Router) {
	api.Get("/ping", func(c *fiber.Ctx) error {
		return c.SendString("pong " + time.Now().Format("2006-01-02 15:04:05"))
	})

	api.Get("/user", func(c *fiber.Ctx) error {
		return c.JSON(dev.GetUser())
	})

	api.Get("/mem", func(c *fiber.Ctx) error {
		return c.JSON(dev.GetMem())
	})

	api.Get("/disk", func(c *fiber.Ctx) error {
		path := c.Query("path", "/")
		return c.JSON(dev.GetDisk(path))
	})

	api.Get("/uptime", func(c *fiber.Ctx) error {
		return c.JSON(dev.GetUptime())
	})

	api.Post("/shutdown", func(c *fiber.Ctx) error {
		log.Println("shutdown...")

		c.JSON(fiber.Map{
			"status": "ok",
		})

		exec.Command("shutdown", "-h", "now").Run()
		return nil
	})

	api.Post("/reboot", func(c *fiber.Ctx) error {
		log.Println("reboot...")

		c.JSON(fiber.Map{
			"status": "ok",
		})

		exec.Command("reboot").Run()
		return nil
	})
}

func Run(embedRoot bool, addr string, port int) {
	if addr != "" {
		fmt.Println("addr:", addr)
	}
	fmt.Println("port:", port)

	app := fiber.New()
	api := app.Group("/api")

	/*
		GET /api/ping
		GET /api/mem
		GET /api/disk?path=/
		GET /api/uptime
	*/
	routerAPI(api)

	if embedRoot {
		app.Use("/", filesystem.New(filesystem.Config{
			Root: web.Root(),
			// Browse: true,
			// Index: "index.html",
		}))
	} else {
		app.Static("/", "./web/www/")
	}

	app.Listen(addr + ":" + fmt.Sprintf("%d", port))
}
